/**
 * @name /www/donations/view.php
 * @author Michael Foss <michael@mikefoss.com>
 * @version 2011.04.27
 * 
 * Client-side functionality for the donations page.
 */

var $donations;
var $donationDialog;
var $donatedItemTemplate;
var $donatedItemsTemplate;
var $donatedItemDialog;
var $itemSearchWidget;
var $donatedItemQuantity;
var $addDonatedItemButton;
var $action;
var $donationId;
var $donatedItemId;

/**
  * Set closures.
  */
$(function() {
  $donations = $('#Donations');
  $donationDialog = $('#DonationDialog');
  $donatedItemDialog = $('#DonatedItemDialog');
  $donatedItemQuantity = $donatedItemDialog.find('input.Quantity');
  $addDonatedItemButton = $('#AddDonatedItemButton');
  $action = $('#Action');
  $donatedItemTemplate = $('#DonatedItemTemplate');
  $donatedItemsTemplate = $('#DonatedItemsTemplate');
  $itemSearchWidget = $('.ItemSearchWidget');
  $donationId = $('#DonationId');
  $donatedItemId = $('#DonatedItemId');
});

/**
  * Prepare message box dialog.
  */
$(function() {
  $('#MessageBox')
    .dialog({
      modal: true,
      autoOpen: false,
      buttons: {
        OK: function() {
          $(this).dialog('close');
        }
      }
    });
});

/**
  * Add icon to TableTools buttons.
  */
function formatTableToolsButton(node, icon) {
  $node = $(node);
	$node.attr('class', 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary');
	$node.children().first().addClass('ui-button-text');
	$node.prepend("<span class='ui-button-icon-primary ui-icon "+icon+"'></span>");
  $node.css('margin-right', '.3em');
}

/**
  * Donations table.
  */
$(function() {
  // Fill the progress bars in the donations table
  $.each($('.ProgressDiv'), function() {
    var $this = $(this);
    var percent = $this.find('input[type=hidden]').val() * 1;
    $this.progressbar({
      value: percent
    });
  });

  // Activate the Add Donations button
  $('.ViewDonationButton')
    .button({
      label: 'View',
      icons: {
        primary: 'ui-icon-search'
      }
    })
    .click(function() {
      openDonateDialog($(this).closest('tr').find('input.DonationId').val());
    });

  // Draw the donations table
  $donations
    .dataTable({
      bJQueryUI: true,
      sPaginationType: 'full_numbers',
      aaSorting: [[2, 'desc']],
      sDom: '<"H"Tfr>t<"F"ip>',
      oTableTools: {
        sSwfPath: '../media/swf/copy_cvs_xls_pdf.swf',
        aButtons: [
          { sExtends: 'copy', "fnInit": function(node) { formatTableToolsButton(node, 'ui-icon-copy'); } },
          { sExtends: 'print', "fnInit": function(node) { formatTableToolsButton(node, 'ui-icon-print'); } },
          { sExtends: 'xls', "fnInit": function(node) { formatTableToolsButton(node, 'ui-icon-disk'); } },
          { sExtends: 'pdf', "fnInit": function(node) { formatTableToolsButton(node, 'ui-icon-disk'); } },
          { sExtends: 'csv', "fnInit": function(node) { formatTableToolsButton(node, 'ui-icon-disk'); } }
          // {
            // sExtends: "collection",
            // sButtonText: "Save",
            // aButtons: ["xls", "pdf", "csv"]
          // }
        ]
      }
    })
  // Show Donor column only if admin
  $donations
    .fnSetColumnVis(4, isAdmin());
  
  // Activate the Add Donations button
  $('#AddDonationButton')
    .button({
      label: 'New Donation',
      icons: {
        primary: 'ui-icon-circle-plus'
      }
    })
    .click(function() {
      openDonateDialog(-1);
    });
});

/**
  * Edit donation dialog.
  */
$(function() {
  // Activate dialog
  $donationDialog.dialog({
    autoOpen: false,
    modal: true,
    width: 900,
    buttons: {
      OK: function() {
        if ($action.val() == 'Update' || $action.val() == 'Add')
          updateDonation();
        else
          $(this).dialog('close');
      },
      Cancel: function() {
        $(this).dialog('close');
      }
    }
  });
  $donationDialog.bind('submit', function() {
    $(this).find('.ui-dialog-buttonset .ui-button:first').click();
    return false;
  });

  // Activate the add donated item button for everybody
  $addDonatedItemButton
    .button({
      icons: {
        primary: 'ui-icon-circle-plus'
      },
      label: 'Add Item'
    })
    .click(function() {
      // Clear the search widget
      $('.ItemSearchWidget').data('clearSearch')();
      openDonatedItemDialog(-1, $(this).closest('tr'));
      $donatedItemDialog.dialog('open');
    });

  // Activate the delete donation button for admins
  $('#DeleteDonationButton')
    .button({
      icons: {
        primary: 'ui-icon-trash'
      },
      label: 'Delete'
    })
    .click(function() {
      $action.val('Delete');
      $donationDialog.find('form')[0].submit();
      return false;
    });

  // Permanently add Edit Donated Item functionality
  $('.EditDonatedItemButton').live('click', function() {
    $row = $(this).closest('tr');
    openDonatedItemDialog($row.find('input.DonatedItemId').val(), $row);
    return false;
  });

  // Permanently add Delete Donated Item functionality
  $('.DeleteDonatedItemButton').live('click', function() {
    $donatedItems.fnDeleteRow($(this).closest('tr')[0]);
    return false;
  });
});

/**
  * Edit donated item dialog.
  */
$(function() {
  // Activate dialog
  $donatedItemDialog.dialog({
    autoOpen: false,
    modal: true,
    width: 500,
    height: 400,
    title: 'Add Item',
    buttons: {
      OK: function() {
        submitDonatedItem();
      },
      Cancel: function() {
        $(this).dialog('close');
      }
    },
    close: function() {
      $donationDialog
        .find('.EditedItem')
        .removeClass('EditedItem');
    }
  });
  $donatedItemDialog.bind('submit', function() {
    $(this).find('.ui-dialog-buttonset .ui-button:first').click();
    return false;
  });

  // Remove the first tag from the tags filter in the Item Search Widget;
  // for some reason, it gets selected when dialog'd
  //
  // UPDATE: Actually, this was probably a bug,
  // either somewhere in the HTML structure or elsewhere in JS-land;
  // code is here for reference only. ~MF 2011.04.25
  /*
  var $isw_select = $donatedItemDialog.find('.ItemSearchWidget select.ItemSearchWidget_TagsSelect');
  $.each($isw_select.find('option:selected'), function(i, $opt) {
    $isw_select.remove($opt.val());
  });
  */
});

function openDonateDialog(donationId) {
  if ($donationDialog.dialog('isOpen'))
    $donationDialog.dialog('close');
  $donationDialog.dialog('option', 'title', (donationId != -1 ? 'Donation #' + donationId : 'New Donation'));
  $action.val(donationId != -1 ? 'Update' : 'Add');
  if (donationId != -1)
    $.post(
      'index.php',
      {
        Action: 'Ajax_GetDonation',
        DonationId: donationId
      },
      openDonateDialog_callback,
      'json'
    );
  else {
    donation = {
      DonationId: 0,
      User: {
        FirstName: '',
        LastName: ''
      },
      DateDonated: '',
      DonatedItems: []
    }
    openDonateDialog_callback(donation);
  }
}

function openDonateDialog_callback(donation) {
  // Remove the old table
  $('#DonatedItems_wrapper').remove();
  $donationId.val(donation.DonationId);
  $donationDialog.find('#DonorName').text('Donor: ' + donation.User.FirstName + ' ' + donation.User.LastName);
  $donationDialog.find('#DateDonated').text('Date Donated: ' + donation.DateDonated);
  $addDonatedItemButton.css('display', (isAdmin() || $action.val() == 'Add') ? 'inline-block' : 'none');
  // Set up the new one based on the template
  $donatedItems = $donatedItemsTemplate.clone().attr('id', 'DonatedItems');
  // Loop through the donated items and add them
  for (i = 0; i < donation.DonatedItems.length; i++) {
    $donatedItem = $donatedItemTemplate.clone();
    $donatedItem.removeAttr('id');
    $donatedItem.find('.EditDonatedItemButton')
      .button({
        icons: {
          primary: 'ui-icon-pencil'
        },
        label: 'Edit'
      });
    $donatedItem.find('.DeleteDonatedItemButton')
      .button({
        icons: {
          primary: 'ui-icon-trash'
        },
        label: 'Delete'
      });
    $donatedItem.find('.DonatedItemId').val(donation.DonatedItems[i].DonatedItemId);
    $donatedItem.find('.ItemId').val(donation.DonatedItems[i].Item.ItemId);
    $donatedItem.find('.Name').text(donation.DonatedItems[i].Item.Name);
    $donatedItem.find('.QuantityPledged').text(donation.DonatedItems[i].QuantityPledged);
    $donatedItem.find('.QuantityReceived').text(donation.DonatedItems[i].QuantityReceived);
    $donatedItem.appendTo($donatedItems);
  }
  $donatedItemsTemplate.after($donatedItems);
  $donatedItems.dataTable({
    bJQueryUI: true,
    bPaginate: false,
    bSort: false,
    bFilter: false,
    bInfo: false
  });
  // Show QuantityReceived column only if admin
  $donatedItems
    .fnSetColumnVis(3, isAdmin());
  // Show Action column only if admin or adding a new donation -
  // existing donations can only be wholly deleted by users
  $donatedItems
    .fnSetColumnVis(0, isAdmin() || $action.val() == 'Add');
  $donationDialog.dialog('open');
}

function openDonatedItemDialog(donatedItemId, $row) {
  $row.addClass('EditedItem');
  if (donatedItemId == -1) {
    donatedItem = {
      DonatedItemId: 0,
      Item: {
        Name: ''
      },
      QuantityPledged: '',
      QuantityReceived: '0'
    }
    openDonatedItemDialog_callback(donatedItem);
  }
  else if (donatedItemId == 0) {
    donatedItem = {
      DonatedItemId: -1,
      Item: {
        Name: $row.find('.Name').text()
      },
      QuantityPledged: $row.find('.QuantityPledged').text(),
      QuantityReceived: $row.find('.QuantityReceived').text()
    }
    openDonatedItemDialog_callback(donatedItem);
  }
  else
    $.post(
      'index.php',
      {
        Action: 'Ajax_GetDonatedItem',
        DonatedItemId: donatedItemId
      },
      openDonatedItemDialog_callback,
      'json'
    );
}

function openDonatedItemDialog_callback(donatedItem) {
  // Update the search widget
  $('.ItemSearchWidget')
    .data('clearSearch')()
    .data('val')(donatedItem.Item.Name);
  $donatedItemQuantity.val(donatedItem.QuantityPledged);
  $('#DonatedItemDialog .QuantityReceived').val(donatedItem.QuantityReceived);
  $donatedItemId.val(donatedItem.DonatedItemId);
  if (donatedItem.DonatedItemId > 0)
    $donatedItemDialog.dialog('option', 'title', 'Donated Item #' + donatedItem.DonatedItemId);
  else
    $donatedItemDialog.dialog('option', 'title', 'New Item');
  $donatedItemDialog.dialog('open');
}

function submitDonatedItem() {
  var
    $dlg = $('#DonatedItemDialog'),
    name = $dlg.find('.ItemSearchWidget_QueryTextBox').val(),
    quantityPledged = $dlg.find('.Quantity').val(),
    quantityReceived = $dlg.find('.QuantityReceived').val();
  $dlg.find('.ui-dialog-buttonset button:first').button('disable');
  $.post(
    'index.php',
    {
      Action: 'Ajax_SubmitDonatedItem',
      DonatedItemId: $donatedItemId.val(),
      Name: name,
      QuantityPledged: quantityPledged,
      QuantityReceived: quantityReceived
    },
    ($donatedItems.find('.EditedItem').length == 0 ? addDonatedItem_callback : updateDonatedItem_callback),
    'json'
  );
  return false;
}

function addDonatedItem_callback(data) {
  console.log(data);
  var
    $dlg = $('#DonatedItemDialog');
  $dlg.find('.ui-dialog-buttonset button:first').button('enable');
  if (!data.Success)
    messageBox(data.Title, data.Message);
  else {
    var rowToAdd = [
      '<a class="DeleteDonatedItemButton"></a> <a class="EditDonatedItemButton"></a><input type="hidden" class="DonatedItemId" value="0" /><input type="hidden" class="ItemId" value="' + data.ItemId + '" />',
      '<span class="Name">' + data.Name + '</span>',
      '<span class="QuantityPledged">' + data.QuantityPledged + '</span>',
      '<span class="QuantityReceived">' + data.QuantityReceived + '</span>'
    ];
    $donatedItems
      .fnAddData(rowToAdd);
    if (data.QuantityReceived === undefined)
      $donatedItems
        .fnSetColumnVis(3, false);
    $donatedItems
      .find('tr:last a.DeleteDonatedItemButton')
      .button({
        label: 'Delete',
        icons: {
          primary: 'ui-icon-trash'
        }
      });
    $donatedItems
      .find('tr:last a.EditDonatedItemButton')
      .button({
        label: 'Edit',
        icons: {
          primary: 'ui-icon-pencil'
        }
      });
    $dlg.dialog('close');
  }
}

function updateDonatedItem_callback(data) {
  var
    $dlg = $('#DonatedItemDialog');
  $dlg.find('.ui-dialog-buttonset button:first').button('enable');
  if (!data.Success)
    messageBox(data.Title, data.Message);
  else {
    if (data.DonatedItemId != -1)
      $row = $donatedItems
        .find('.DonatedItemId[value=' + data.DonatedItemId + ']')
        .closest('tr');
    else
      $row = $donatedItems
        .find('.EditedItem');
    $row
      .find('.ItemId')
      .val(data.ItemId);
    $row
      .find('.Name')
      .text(data.Name);
    $row
      .find('.QuantityPledged')
      .text(data.QuantityPledged);
    $row
      .find('.QuantityReceived')
      .text(data.QuantityReceived);
    $dlg.dialog('close');
  }
}

function updateDonation() {
  var $form, $rows, data;
  // Get the data to add
  data = [];
  $rows = $('#DonationDialog #DonatedItems tbody tr:gt(0)');
  if ($rows.length == 0) {
    messageBox('No Items Added', 'You have donated no items. Please donate some items before submitting a donation by clicking the Add Item button.');
    return false;
  }
  $.each($rows, function(i, row) {
    $row = $(row);
    data.push({
      DonatedItemId: $row.find('.DonatedItemId').val(),
      ItemId: $row.find('.ItemId').val(),
      Name: $row.find('.Name').text(),
      QuantityPledged: $row.find('.QuantityPledged').text(),
      QuantityReceived: $row.find('.QuantityReceived').text()
    });
  });

  // Add all data within the DonationDialog to the form
  $form = $('<form>')
    .attr('method', 'POST')
    .append(
      $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'Action')
        .val($('#Action').val())
    );
  $form
    .append(
      $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'DonationId')
        .val($('#DonationId').val())
    );
  $.each(data, function(i, item) {
    // Add DonatedItemId
    $form.append(
      $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'DonatedItemId_' + i)
        .val(item.DonatedItemId)
    );
    // Add ItemId
    $form.append(
      $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'ItemId_' + i)
        .val(item.ItemId)
    );
    // Add Name
    $form.append(
      $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'Name_' + i)
        .val(item.Name)
    );
    // Add QuantityPledged
    $form.append(
      $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'QuantityPledged_' + i)
        .val(item.QuantityPledged)
    );
    // Add QuantityReceived
    $form.append(
      $('<input />')
        .attr('type', 'hidden')
        .attr('name', 'QuantityReceived_' + i)
        .val(item.QuantityReceived)
    );
  });
  // Submit form
  $form[0].submit();
  return false;
}

function messageBox(title, msg) {
  $mbox = $('#MessageBox');
  $mbox
    .html(msg)
    .dialog('option', 'title', title)
    .dialog('open');
}

function isAdmin() {
  return ($('#__A').css('display') != 'none');
}